/*
 * UserSessionDAO.java
 *
 * Created on June 24, 2007, 3:40 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package jhub.dao;

import java.net.InetAddress;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import jhub.HubSession;
import jhub.UserSession;

/**
 *
 * @author dbotelho
 */
public class UserSessionDAO extends AbstractDAO{
    
    private final PreparedStatement addUserSessionStatement;
    private final PreparedStatement updateUserSessionStatement;
    
    /** Creates a new instance of UserSessionDAO */
    public UserSessionDAO(Connection conn) throws SQLException {
        super(conn);
        this.addUserSessionStatement = conn.prepareStatement("INSERT INTO \"user_session\" (id,hub_session_id,\"user_ip\",user_port,\"start\",\"end\") VALUES(?,?,?,?,?,?)");
        this.updateUserSessionStatement = conn.prepareStatement("UPDATE \"user_session\" SET user_id = ?, \"end\"= ? WHERE id=?");
    }
        
    public void update(UserSession userSession) throws SQLException{
        int i=1;       
        if(userSession.getUser()!=null)
            updateUserSessionStatement.setInt(i++,userSession.getUser().getId());
        else
            updateUserSessionStatement.setNull(i++,java.sql.Types.NULL);
        
        if(userSession.getEnd()!=null)
            updateUserSessionStatement.setLong(i++,userSession.getEnd().getTime());
        else
            updateUserSessionStatement.setNull(i++,java.sql.Types.NULL);
        
        updateUserSessionStatement.setInt(i++,userSession.getSessionID());
        
        System.out.println(updateUserSessionStatement.toString());
        updateUserSessionStatement.executeUpdate();
    }
    
    public void startUserSession(UserSession userSession) throws SQLException{
        int i=1;
        userSession.setSessionID(super.nextValue("user_session_id_seq"));
        addUserSessionStatement.setInt(i++,userSession.getSessionID());
        
        //addUserSessionStatement.setInt(i++,userSession.getUser().getId());
        addUserSessionStatement.setInt(i++,userSession.getHubSession().getSessionID());
        addUserSessionStatement.setString(i++,userSession.getIp());
        
        addUserSessionStatement.setInt(i++,userSession.getPort());
        
        addUserSessionStatement.setLong(i++,userSession.getStart().getTime());    
        if(userSession.getEnd()!=null)
            addUserSessionStatement.setLong(i++,userSession.getEnd().getTime());
        else
            addUserSessionStatement.setNull(i++,java.sql.Types.NULL);
        System.out.println(addUserSessionStatement.toString());
        addUserSessionStatement.executeUpdate();
    }
    
}
